package cc.wsyw126.java.nowcoder.sword_offer;

import java.util.ArrayList;

/**
 * Created by dp on 2017/4/19.
 * 给定一个数组和滑动窗口的大小，找出所有滑动窗口里数值的最大值。
 * 例如，如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3，那么一共存在6个滑动窗口，他们的最大值分别为{4,4,6,6,6,5}；
 * 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个：
 * {[2,3,4],2,6,2,5,1}， {2,[3,4,2],6,2,5,1}， {2,3,[4,2,6],2,5,1}， {2,3,4,[2,6,2],5,1}， {2,3,4,2,[6,2,5],1}， {2,3,4,2,6,[2,5,1]}。
 */
public class MaxInWindows {
    public ArrayList<Integer> maxInWindows(int[] num, int size) {
        ArrayList<Integer> result = new ArrayList<>();
        if (num == null || num.length == 0 || size <= 0 || size > num.length) return result;
        int max = Integer.MIN_VALUE;
        max = getMax(num, 0,size-1, max);
        result.add(max);
        for (int i = size; i < num.length; i++) {
            if (num[i] > max) {
                max = num[i];
            } else {
                if (num[i-size] == max) {
                    max=getMax(num, i-size+1, i,num[i]);
                }
            }
            result.add(max);
        }
        return result;
    }

    private int getMax(int[] num,int begin,  int end, int max) {
        for (int i = begin; i <= end && i < num.length; i++) {
            if (num[i] > max) {
                max = num[i];
            }
        }
        return max;
    }

    public static void main(String[] args) {
        MaxInWindows maxInWindows = new MaxInWindows();
        ArrayList<Integer> integers = maxInWindows.maxInWindows(new int[]{2, 3, 4, 2, 6, 2, 5, 1}, 3);
        for (Integer integer : integers) {
            System.out.print(integer + "\t");
        }
    }
}
